/**
 * Created by Administrator on 2016/10/5.
 */
var TIMEOUT_INS = null;

var rAF_ticking = false; // rAF 触发锁
//豆腐运动 定时器句柄
var move_INS = null;

//游戏开始
var game_START = false;
//是否到达边界 结束游戏
var game_OVER = false;

//游戏结束仅处理一次回调函数
var gameover_ONE = true;

//边界误差
var gamebox_width_ERROR = 15;
var gamebox_height_ERROR = 20;

var game_operate_NOT = false;
var game_operate_ONE = true;
var game_operate_TIME = null;

//游戏时间
var game_TIME = 0;

/**
 * 倒计时
 * @HTML {Dom}
 * @param {function} 回调函数,参数：当前dom对象
 * @return {}
 */
;!function($){
    $.fn.countDown = function(callback){
        var callback = callback || new Function();
        var timestamp = [];
        this.each(function(index,el){
            //大于0的时间戳可倒计时
            timestamp.push( $(this).data('timestamp'));
            if( timestamp[index] >0 ){
                if( $(this).data('isCountDown') ){
                    return ;
                }
                $(this).data('isCountDown',true);
                create(timestamp[index],$(this),callback);
            }else{
                $(this).find('.second,.msec').text('00');
            }
        })
        function create(timestamp,$el){
            $.countDownClear = setInterval(function(){
                timestamp = timestamp - 100;
                var s = parseInt(timestamp / 1000); //秒
                var m = Math.floor(timestamp % 1000)/10; //毫秒
                //补0处理 7 -> 07
                m = m <= 9 ? "0" + m : m;
                s = s <= 9 ? "0" + s : s;
                //显示
                $el.find('.msec').text(m);
                $el.find('.second').text(s);
                if(timestamp <= 0){
                    clearInterval($.countDownClear);
                    callback.call($el.get(0));
                    return ;
                }
            },100)
        }
    }
}(window.jQuery)

//重力感应
var shake = function () {
    //移动的加速度
    var hasDeviceMotion = 'ondevicemotion' in window;
    //移动的角度
    var hasDeviceOrientation = 'ondeviceorientation' in window;
    /*
     DeviceOrientationEvent.alpha 表示设备沿z轴上的旋转角度，范围为0~360。
     DeviceOrientationEvent.beta 表示设备在x轴上的旋转角度，范围为-180~180。
     DeviceOrientationEvent.gamma 表示设备在y轴上的旋转角度，范围为-90~90。
    * */
    if (hasDeviceOrientation) {
        window.addEventListener('deviceorientation',throttle(function (e) {
            //游戏开始
            if (!game_START) {
                return false;
            }
            //游戏结束
            if (game_OVER) {
                return false;
            }
            //无事件对象
            if(!e) {
                return false;
            }
            game(e.gamma,e.beta);
            e.preventDefault();
        },200,200), false);
    }
/*    if (hasDeviceOrientation) {
        window.addEventListener('deviceorientation', function (e) {
            //raf方式
            if(!rAF_ticking) {
                requestAnimationFrame(function () {
                    game(e.gamma,e.beta);
                });
                rAF_ticking = true;
            }
            e.preventDefault();
        }, false);
    }*/
}

// 简单的节流函数 节流函数多了一个 mustRun 属性，代表 mustRun 毫秒内，必然会触发一次 handler
function throttle(func, wait, mustRun) {
    var timeout,
        startTime = new Date();
    return function() {
        var context = this,
            args = arguments,
            curTime = new Date();
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔，触发 handler
        if(curTime - startTime >= mustRun){
            func.apply(context,args);
            startTime = curTime;
            // 没达到触发间隔，重新设定定时器
        }else{
            timeout = setTimeout(func, wait);
        }
    };
};

// 匀速运动
var move = function ( speedX , speedY) {
    var tofu = $('#tofu');
    var dishWidth = $('#dish').width();
    var dishHeight = $('#dish').height();
    var posX = tofu.position().left.toFixed(2);
    var posY = tofu.position().top.toFixed(2);
    var startSx = ( posX - dishWidth/2 ).toFixed(2);
    var startSy = ( posY - dishHeight/2 ).toFixed(2);


    //如果是平放 给一个速度
    if( Math.abs(speedX) < 0.5 &&  Math.abs(speedY) < 0.5 ){
        //
        if(game_operate_ONE){
            //alert('operate')
            //两秒没操作
            setTimeout(function () {
                // alert('平放')
                game_operate_NOT= true;
                game_operate_TIME = setTimeout(function () {
                    game_operate_NOT = false;
                    game_operate_ONE = true;
                },1000)
            },2000)
            game_operate_ONE = false;
        }

    }else{
        if(speedX > 30 || speedY > 30){
            game_operate_NOT = false;
        }
    }
    //没平放
    if(game_operate_NOT){
        //$('#tofu').css({'background-image':'url(./images/tofu-fun.png)'})
        if( speedX < 0){
            speedX = speedX - 10;
        }else{
            speedX = speedX + 10;
        }
        if( speedY < 0){
            speedY = speedY - 10;
        }else{
            speedY = speedY + 1;
        }
    }

    var Sx = parseFloat(startSx) + parseFloat (speedX * 0.1);
    var Sy = parseFloat(startSy) + parseFloat (speedY * 0.1);

    if (move_INS) {
        clearInterval(move_INS);
    }
    move_INS = setInterval(function () {
        posX = tofu.position().left.toFixed(2);
        posY = tofu.position().top.toFixed(2);
        startSx = ( posX - dishWidth/2 ).toFixed(2);
        startSy = ( posY - dishHeight/2 ).toFixed(2);
        Sx = parseFloat(startSx) + parseFloat (speedX * 1.3);
        Sy = parseFloat(startSy) + parseFloat (speedY * 1.3);
        //边界
        if(
            posX  <= gamebox_width_ERROR                 ||
            posY  <= gamebox_height_ERROR                ||
            ( posX > dishWidth - gamebox_width_ERROR )   ||
            ( posY > dishHeight - gamebox_height_ERROR ) ||
            game_OVER ==  true
        ) {
            //游戏结束
            gameOver(false);
            if (game_OVER) {
                clearInterval(move_INS);
            }
            //游戏结束状态
            game_OVER = true;
            return ;
        }
        //换表情
        gameTofuFace(speedX,speedY);
        tofu.css({ x: Sx, y: Sy });
    },60)
}

//游戏部分
var game = function (x,y) {
    var x = x.toFixed(2);
    var y = y.toFixed(2);
    move(x,y);
    //
    rAF_ticking = false;
}
//游戏初始化
var gameInit = function () {
    //关闭提示开始游戏
    $('#close').click(function () {
        $('#game-tips').hide();
        $('#game-rule').fadeIn(300);
        //进入游戏之后销毁之前的动画
        dispose();
    })
    //进入游戏
    $('#btn-game-start').click(function () {
        $('#game-rule').fadeOut(300);
        setTimeout(function () {
            game_START = true;
            $('.timer-box .pointer').addClass('animated');
            gameTimer();
        },1000)
        playMusic.musicInit();
    })
    //重新开始
    $('.game-restart').click(function () {
        gameRestart();
    })
    //分享提示事件
    $('.popup.share').click(function () {
        $(this).fadeOut(300);
    })

}
//计时器
var gameTimer = function () {
    $('#timer').countDown(function () {
        game_OVER = true;
        gameOver(true);
    })
}

//游戏结束
var gameOver = function (result) {
    //计时器停止
    clearInterval($.countDownClear);
    clearInterval(move_INS);
    //计时器指针停止
    $('.timer-box .pointer').removeClass('animated');
    if (gameover_ONE) {
        //通过
        if (result) {
            setTimeout(function () {
                $('#game-pass').removeClass('hide').addClass('show');
            },500)

        }else{
            //失败
            setTimeout(function () {
                $('#game-loser').removeClass('hide').addClass('show');
                //显示游戏结果
                game_TIME = 60-$('#timer .second').text();
                $('#score').text(game_TIME);
            },500)
        }
        gameover_ONE = false;
    }
}
//更换豆腐表情
var gameTofuFace = function (x,y) {
    var x = parseInt(x);
    var y = parseInt(y);
    var $tofu = $('#tofu');
    if (Math.abs(x) > Math.abs(y)) {
         //向左
         if(x < 0) {
             $tofu.css({'background-image':'url(./images/left.png)'})
         }
         //向右
         if(x > 0) {
             $tofu.css({'background-image':'url(./images/right.png)'})
         }
    }
    if(Math.abs(x) < Math.abs(y)) {
        //向上
        if(y < 0) {
            $tofu.css({'background-image':'url(./images/up.png)'})
        }
        //向下
        if(y > 0) {
            $tofu.css({'background-image':'url(./images/down.png)'})
        }
    }
/*    if(Math.abs(x)<3 && Math.abs(y)<3) {
        $tofu.css({'background-image':'url(./images/tofu-fun.png)'})
    }*/
}

var gameRestart =function () {
    /*状态重置*/
    // rAF 触发锁
    rAF_ticking = false;
    //豆腐运动 定时器句柄
    move_INS = null;
    //游戏开始
    game_START = true;
    //是否到达边界 结束游戏
    game_OVER = false;
    //游戏结束仅处理一次回调函数
    gameover_ONE = true;


    //豆腐位置复位
    $('#tofu').css({ x: 0, y: 0 });
    //关闭弹窗
    $('#game-pass,#game-loser').removeClass('show').addClass('hide');
    //1s钟之后自动开始定时器
    $('#timer').data('isCountDown',false);
    $('#timer').find('.second').text(59);
    $('#timer').find('.msec').text(99);
     setTimeout(function () {
         gameTimer();
     },1000)
}

//分享提示
var shareTips = function () {
    $('.popup.share').fadeIn(300);
}


//帧动画
var frameAnimation = function () {
    var animation = window.animation;

    var images = ['./images/sprites-somg.png','./images/sprites-fire.png','./images/sprites-tofu.png'];
    //烟雾
    var $smog = $('#smog')[0];
    var smogMap = ["0 0", "-3.05 0", "-6.1 0", "-9.15 0","-12.2 0"];
    window.smogAnimation = animation().loadImage(images).changePosition($smog, smogMap, images[0]).wait(100).repeatForever();
    smogAnimation.start(500);
    //火
    var $fire = $('#fire')[0];
    var fireMap = ["-0.02 0", "-3.29 0", "-6.56 0", "-9.83 0","-13.1 0","-16.37 0", "-19.6 0", "-22.79 0","-26 0", "-29.25 0","-32.52 0","-35.79 0", "-39.06 0", "-42.33 0","-45.63 0"];
    window.fireAnimation = animation().loadImage(images).changePosition($fire, fireMap, images[1]).repeatForever();
    fireAnimation.start(200);
    //豆腐
    var $tofu = $('#tofu-ku')[0];
    var tofuMap = ["-0.01 0", "-2.8 0", "-5.6 0", "-8.4 0","-11.18 0","-13.95 0", "-16.75 0", "-19.56 0","-22.35 0", "-25.15 0"];
    window.tofuAnimation = animation().loadImage(images).changePosition($tofu, tofuMap, images[2]).repeatForever();
    tofuAnimation.start(230);

}
//销毁帧动画
var dispose = function () {
    smogAnimation.dispose();
    fireAnimation.dispose();
    tofuAnimation.dispose();
}
/*
*
*   游戏音乐
* */
var gameAudio = function(){
    var music = $('#audio-music')[0];

    $("#music").bind("touchend",function(){
        if (music.paused){
            music.play();
            $(this).removeClass('off');
        }
        else{
            music.pause();
            $(this).addClass('off');
        }
    })

    this.musicInit = function () {
        if (music.paused){
            music.play();
            $(this).removeClass('off');
        }
        else{
            music.pause();
            $(this).addClass('off');
        }
    }
    this.play = function () {
        music.play();
    }
    this.pause = function () {
        music.pause();
    }
}

$(function () {
    //loading
    var loader=new createjs.LoadQueue();
    loader.on("complete",function () {
        $('.loading').fadeOut(300);
        $('.page.page-1').fadeIn(300);
        //页面切换 第一页切换至第二页
        setTimeout(function () {
            $('.slogan-3,.pan').hide(0);
            $('.slogan-1,.page-1 .box-2').fadeIn(500)
        },3000)
    });
    loader.on('progress',function (e) {
        var percentage = parseInt(e.progress * 100) + '%';
        $('#loading-progress').text( percentage )

    })
    loader.loadManifest([
        {"src": "images/slogan-2.png", "id": "test1"},
        {"src": "images/slogan-1.png", "id": "test2"},
        {"src": "images/sprites-fire.png", "id": "test3"},
        {"src": "images/sprites-somg.png", "id": "test4"},
        {"src": "images/sprites-tofu.png", "id": "test4"},
        {"src": "images/pan.png", "id": "test5"},
        {"src": "images/logo.png", "id": "test6"},
        {"src": "images/tofu-pan.png", "id": "test7"},
        {"src": "images/person-1.png", "id": "test8"},
        {"src": "images/person-2.png", "id": "test9"},
        {"src": "images/person-3.png", "id": "test10"},
        {"src": "images/left.png", "id": "test11"},
        {"src": "images/right.png", "id": "test12"},
        {"src": "images/up.png", "id": "test13"},
        {"src": "images/down.png", "id": "test14"}
    ])

    //重力感应
    frameAnimation();
    shake();
    gameInit();
    //音乐
    window.playMusic = new gameAudio();
    //游戏开始
    $('#btn-game-begin').click(function () {
        $('.page.game').fadeIn(500);
        $('.page.page-1').hide();
    })

})

